<template>
  <div>
    <el-card>
      <!--头部区域-->
      <el-row :gutter="20" type="flex">
        <el-col>
          <el-form :inline="true" ref="searchFrom" :model="topForm">
            <el-form-item label="课程名称：" prop="course_name">
              <el-input v-model="topForm.course_name" placeholder="" size="small"></el-input>
            </el-form-item>
            <el-form-item label="任课老师：" prop="course_teacher">
              <el-input v-model="topForm.teacher_name" placeholder="" size="small"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="courseInfo()" size="small">查询</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="topFormClear()" size="small">重置</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="dialogVisible=true;" size="small">新增</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <!--数据展示表格-->
      <el-table
        :data="tableData"
        border
        max-height="500px"
        style="width: 100%">
        <el-table-column
          label="#"
          type="index"
          width="50px"
          align="center">
        </el-table-column>
        <el-table-column
          prop="course_name"
          label="课程">
        </el-table-column>
        <el-table-column
          prop="course_fengmian"
          label="封面">
          <template slot-scope="scope">
            <div>
              <el-popover placement="right" trigger="hover">
                <el-image
                  style="height: 300px"
                  :src="scope.row.course_fengmian"
                  :fit="contain">
                </el-image>
                <el-image
                  slot="reference"
                  style="width:100px ;height: 100px"
                  :src="scope.row.course_fengmian"
                  :fit="contain">
                </el-image>
              </el-popover>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="course_startDate"
          label="开始日期"
          width="180">
        </el-table-column>
        <el-table-column
          prop="course_endDate"
          label="结束日期"
          width="180">
        </el-table-column>
        <el-table-column
          prop="course_teacher"
          label="老师"
          width="180">
        </el-table-column>
        <el-table-column
          prop="course_status"
          label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.course_status === 'true'">已开课</span>
            <span v-else>未开课</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="caozuo"
          label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeCourseById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!--翻页和条数切换-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
      <!--新增/编辑表单-->
      <div>
        <el-dialog
          @close="dialogFormClear"
          :visible.sync="dialogVisible"
          width="50%"
          >
          <div slot="title" class="dialog-title" >
            <span v-if="dialogTitle==='编辑课程'">编辑课程</span>
            <span v-else>新增课程</span>
          </div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="课程名称">
              <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="任课老师">
              <el-input v-model="form.course_teacher"></el-input>
            </el-form-item>
            <el-form-item label="学期时间">
              <div class="block">
                <el-date-picker
                  v-model="form.dateForm"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="getTime">
                </el-date-picker>
              </div>
            </el-form-item>
            <el-form-item label="课程封面">
              <Upload ref="upload"
              @imgChange="getFilePath"
              :fp="form.filepath"
              :fn="form.filename"
              />
            </el-form-item>
            <el-form-item label="开课状态">
              <el-switch v-model="form.open" active-value="true" inactive-value="false"></el-switch>
            </el-form-item>
            <el-form-item>
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="dialogVisible = false;addOrEditForm()">确 定</el-button>
            </el-form-item>
          </el-form>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
  import {Form} from "element-ui";
  import Upload from "../../components/Upload.vue";

  export default {
    components: {Upload},
    data() {
      return {
        // <!--底部翻页数据内容-->
        tableData: [],
        allData: [],
        current:1,
        total: 0,
        size:10,
        // <!--顶部搜索栏输入内容-->
        topForm:{
          course_name:'',
          teacher_name:'',
        },
        dialogVisible:false,
        dialogTitle:'',
        //dialog新增编辑表单
        form:{
          // 新增/编辑状态
          addOrEdit:'',
          id:'',
          name:'',
          course_teacher: '',
          dateForm:['', ''],
          open:false,
          filepath:'',
          filename:'',
        },
        // 默认dialog空表单，提供关闭回调
        defaultForm:{
          // 新增/编辑状态
          addOrEdit:'',
          id:'',
          name:'',
          course_teacher: '',
          dateForm:['', ''],
          open:false,
          filepath:'',
          filename:'',
        },
      };
    },
    mounted:function () {
      this.courseInfo()
    },
    methods: {
      //删除课程功能
      removeCourseById(id){
        this.$confirm('确定要删除该课程吗', '提示',{
          confirmButtonText:'确定',
          cancelButtonText:'取消',
          type:'warning'
        }).then(()=>{
          this.$axios.delete('api/course/del',{
            params:{id: id},
          }).then((res)=>{
            if (res.data['respCode']==='000000'){
              this.$message({ message:'删除成功',type:'success'});
              location.reload()
            }else {
              this.$message.error(res.data['respMsg'])
            }
          });
        })
          .catch(()=>{
            this.$message({ type:"info",message:'已取消删除'})
          })
      },
      //点击编辑按钮后查询ID并给表单赋数据，打开dialog
      showEditDialog(id) {
        this.dialogTitle = '编辑课程'
        this.addOrEdit = '编辑'
        this.$axios.get('api/course/info',{
          params:{id: id}
        }).then((res)=>{
          if (res.data['respCode']==='000000'){
            this.form.id = id
            this.form.name = res.data['list'][0]['course_name']
            this.$set(this.form,'open', res.data['list'][0]['course_status'])
            this.form.filepath = res.data['list'][0]['course_fengmian']
            this.form.filename = res.data['list'][0]['course_imgName']
            this.form.course_teacher = res.data['list'][0]['course_teacher']
            this.$set(this.form.dateForm,0,res.data['list'][0]['course_startDate'])
            this.$set(this.form.dateForm,1,res.data['list'][0]['course_endDate'])
            this.dialogVisible=true
          }else {
              this.$message.error(res.data['respMsg'])
          }
        })
      },
      //获取新增表单中的开始时间和结束时间
      getTime() {
        this.form.dateForm[0] = this.form.dateForm[0]
        this.form.dateForm[1]= this.form.dateForm[1]
      },
      //获取后端response中的文件路径，upload路由通信，见Upload组件
      getFilePath(filepath, filename) {
        this.form.filepath = filepath
        this.form.filename = filename
      },
      //dialog关闭回调重置dialog表单数据
      dialogFormClear() {
        this.form = Object.assign({}, this.defaultForm)
        // el-date组件列表，需要用set方法进行重置
        this.$set(this.form.dateForm,0,'')
        this.$set(this.form.dateForm,1,'')
      },
      //重置按钮操作
      topFormClear() {
        this.$refs.searchFrom.resetFields()
      },
      //新增和编辑操作
      addOrEditForm() {
        // 编辑表单
        if (this.form.id){
          this.$axios.get('api/course/edit/', {
          params: {id:this.form.id, name:this.form.name, course_teacher:this.form.course_teacher, startDate:this.form.dateForm[0],
            endDate:this.form.dateForm[1],open:this.form.open, filepath:this.form.filepath, filename:this.form.filename}
        }).then((response)=>{
          var res = response.data
          if (res['respCode'] === '000000'){
            this.$message.success('修改成功')
            this.courseInfo()
          }else {
            this.$message.error(res['respMsg'])
          }
        })
        }else {
          // 新增表单
          this.dialogTitle='新增课程'
          this.$axios.get('api/course/add/', {
            params: {
              name: this.form.name, course_teacher: this.form.course_teacher, startDate: this.form.dateForm[0],
              endDate: this.form.dateForm[1], open: this.form.open, filepath: this.form.filepath,filename: this.form.filename
            }
          }).then((response) => {
            var res = response.data
            if (res['respCode'] === '000000') {
              this.courseInfo()
              this.$message.success('新增成功')
            } else {
              this.$message.error('新增失败')
              console.log(res['respMsg'])
            }
          })
        }
      },
      // <!--展示后端数据列表-->
      //查询按钮操作
      courseInfo() {
        this.$axios.get('api/course/info/',{
          params: {course_name:this.topForm.course_name, course_teacher:this.topForm.teacher_name}
            }).then((response)=>{
              var res = response.data
              if (res['respCode']==='000000'){
                this.allDate = res['list']
                // <!--slice切片展示当页数据-->
                this.tableData = this.allDate.slice(
                  (this.current-1)* this.size,
                  this.current * this.size
                );
                this.total = this.allDate.length
                console.log(res['list'])
              }else {
                console.log(res['respMsg'])
              }
            })
          },
      //页面条数切换钩子
      handleSizeChange(val) {
        this.size = val
        this.current = 1
        this.courseInfo()
        console.log(`每页 ${val} 条`);
      },
      //页码切换的钩子
      handleCurrentChange(val) {
        this.current = val
        this.courseInfo()
        console.log(`当前页: ${val}`);
      },
    },
  }
</script>

<style scoped>
.el-pagination {
  float: right;
  padding: 10px;
}
</style>
